import {
	flagHttpUrl,
	getCurrentPagePath
} from "../utils/util"
import {
	BASE_URL,
	MOCK_USER_DATA
} from "../utils/constant.js"
// import { userStore } from "../stores/userStore";
// let storeUser = userStore();
let loadingCount = 0;
const hideRequestingLoading = () => {
	let tmp_loading_count = loadingCount - 1;
	if (tmp_loading_count <= 0) {
		loadingCount = 0;
		uni.hideLoading();
	} else {
		loadingCount = tmp_loading_count
	}
}
const canMockUserPage = ["pages/index/index", "pages/about/index"]
/**
 * 请求
 * @param options 
 * @returns 
 */
let request11=0;
const request = async (options, skipToken = false) => {
	return new Promise(async (resolve, reject) => {
		if (!skipToken) {
			// TODO:先获取Token数据
			// let systemUserInfo = await storeUser.systemLogin()

		}
		// 
		let urlPreFix = "";
		if (!flagHttpUrl) {
			urlPreFix = BASE_URL;
		}
		if (options.enableLoading) {
			loadingCount++;
			uni.showLoading();
		}

		let headers = {
			'Content-Type': 'application/x-www-form-urlencoded',
		}
		if(!options.resetCookie){
			headers.cookie= uni.getStorageSync("sessionid") //读取本地保存好的上一次cookie
		}
		let headerConfig = Object.assign({}, headers, options?.headers || {})

		const requestConfig = {
			url: `${BASE_URL}${options.url}`,
			method: options.method || 'POST',
			data: options.data || null,
			dataType: "json",
			header: headerConfig,
		}
		// console.log(requestConfig,options, '>>>requestConfig')
		uni.request({
			...requestConfig,
			success: async (res) => {
				// console.log(JSON.stringify(requestConfig));
				// console.log(JSON.stringify(res),">>>>resquestConfig,res")
				if (options.enableLoading) {
					hideRequestingLoading()
				}
				var cookie = res.header["Set-Cookie"];
				if (cookie != null) {
					uni.setStorageSync("sessionid", res.header[
						"Set-Cookie"]); //服务器返回的Set-Cookie，保存到本地
				}
				// console.log(res,requestConfig, ">>>requestConfig...data")
				const respData = res.data
				console.log('respData>>>',respData)

				// if the custom code is not 20000, it is judged as an error.
				if (respData !== '') {
					if (respData.status !== 0) {
						// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
						if (respData.status === 999201) {
							let path = getCurrentPagePath();
							console.log(path,"reLoginPath>>")
							if (canMockUserPage.includes(path)) {
								let reLoginRes = await post({
									...MOCK_USER_DATA
								},true)
								console.log(reLoginRes,"reLoginRes>>>>>")
								console.log(options,skipToken,">>>")
								resolve(request(options, skipToken))
								return 
							}
							//   // to re-login
							//   let reLoginRes = await storeUser.reLogin(false);
							//   return request(options, skipToken);
							loadingCount = 0;
							uni.hideLoading()


							uni.navigateTo({
								url: `/pages/login/index?redirect=${encodeURIComponent(path)}`,
								success: () => {
									uni.hideLoading()
								}
							})
							return;
						} else {
							//   // Message({
							//   //   message: res.msg || 'Error',
							//   //   type: 'error',
							//   //   duration: 5 * 1000
							//   // })
							//   uni.showToast({
							//     title: respData.msg || 'Error',
							//     icon: "none",
							//     duration: 5000
							//   })
						}
						uni.showToast({
							title: respData.msg || 'Error',
							icon: "none",
							duration: 5000
						})
						return reject(new Error(respData.msg || 'Error'))
					} else {
						if (options.notReturnData) {
							return resolve(respData)
						}
						let responseData = respData.returnData;
						if (respData.big_data) {
							responseData = {
								returnData: responseData,
								big_data: respData.big_data
							}
						}
						return resolve(responseData);
					}
				}


				// if(res&&res.data&&res.data.status==999201){
				//   requestCount++;
				//   let reLoginRes=await storeUser.reLogin(false);
				//   return request(options,skipToken);
				// }
				// resolve(res.data)

			},
			fail: (error) => {
				if (options.enableLoading) {
					hideRequestingLoading();
				}

				if (options.failedResolve) {
					resolve(error);
				} else {
					reject(error)
				}
			}
		})
	})
}

/**
 * 
 * @param options 
 * @returns 
 */
const post = (options = {}, skipToken = false) => {
	// console.log(options, "")
	return request(Object.assign({}, options, {
		method: 'POST'
	}), skipToken);
}

/**
 * 
 * @param options 
 * @returns 
 */
const get = (options = {}, skipToken = false) => {

	return request(Object.assign({}, options, {
		method: 'GET'
	}), skipToken);
}


export default {
	post,
	get
}